const mongoose = require('mongoose');
const Schema = mongoose.Schema;

/**
 * 提醒记录模型
 * 用于存储用户的各类健康提醒设置
 */
const ReminderSchema = new Schema({
  userId: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true,
    index: true
  },
  title: {
    type: String,
    required: true,
    trim: true
  },
  type: {
    type: String,
    enum: ['medication', 'measurement', 'exercise', 'water', 'assessment'],
    default: 'medication'
  },
  hour: {
    type: Number,
    required: true,
    min: 0,
    max: 23
  },
  minute: {
    type: Number,
    required: true,
    min: 0,
    max: 59
  },
  repeatDays: {
    type: [Number],
    default: [0, 1, 2, 3, 4, 5, 6], // 默认每天重复 (0-6 代表周日到周六)
    validate: {
      validator: function(days) {
        if (!days || days.length === 0) return true; // 允许空数组（不重复）
        return days.every(day => day >= 0 && day <= 6);
      },
      message: '重复日期必须是0-6的数字，代表周日到周六'
    }
  },
  enabled: {
    type: Boolean,
    default: true
  },
  priority: {
    type: Number,
    min: 1,
    max: 3,
    default: 2 // 1=低, 2=中, 3=高
  },
  note: {
    type: String,
    trim: true
  },
  completionHistory: [{
    date: {
      type: Date,
      required: true
    },
    status: {
      type: String,
      enum: ['completed', 'missed', 'snoozed'],
      default: 'completed'
    },
    completedAt: {
      type: Date
    }
  }],
  isCompleted: {
    type: Boolean,
    default: false
  },
  nextOccurrence: {
    type: Date
  },
  lastSent: {
    type: Date
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
}, {
  timestamps: true // 自动添加 createdAt 和 updatedAt 字段
});

// 添加索引以提高查询性能
ReminderSchema.index({ userId: 1, type: 1 });
ReminderSchema.index({ userId: 1, nextOccurrence: 1 });
ReminderSchema.index({ userId: 1, isCompleted: 1 });

// 创建和导出模型
const Reminder = mongoose.model('Reminder', ReminderSchema);
module.exports = Reminder; 